// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2021 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------

import {
  HTTP_REQUEST_URL,
  HEADER,
  TOKENNAME,
  HEADERPARAMS,
} from "@/config/app";
import { toLogin, checkLogin } from "../libs/login";
import store from "../store";

function replaceHttpWithHttps(obj) {
  for (let key in obj) {
    if (typeof obj[key] === "string" && obj[key].startsWith("http://")) {
      // // #ifdef MP-WEIXIN
      // obj[key] = obj[key].replace("http://8.134.79.41:8080", 'https://prodapi.huikexin.fun');
      // // #endif
      // // #ifndef MP-WEIXIN
      // obj[key] = obj[key].replace("http://8.134.79.41:8080", HTTP_REQUEST_URL);
      obj[key] = obj[key].replace(
        "http://8.134.79.41:8080",
        "https://prodapi.huikexin.fun"
      );
      // #endif
      // obj[key] = obj[key].replace(
      //   "http://8.134.79.41:8080/crmeb/public/maintain/",
      //   "https://app-cangshu.oss-rg-china-mainland.aliyuncs.com/asssets/crmeb/public/maintain"
      // );
      if (obj[key].startsWith("http://8.134.79.41:9000/app")) {
        obj[key] = obj[key].replace(
          "http://8.134.79.41:9000/app",
          "https://app-cangshu.oss-rg-china-mainland.aliyuncs.com/asssets/img"
        );
      }
    } else if (typeof obj[key] === "object" && obj[key] !== null) {
      replaceHttpWithHttps(obj[key]); // 递归处理嵌套对象
    }
  }
}
/**
 * 发送请求
 */
function baseRequest(
  url,
  method,
  data,
  { noAuth = false, noVerify = false, newOrder },
  params,
  str
) {
  let Url = HTTP_REQUEST_URL,
    header = HEADER;
  if (params != undefined) {
    header = HEADERPARAMS;
  }
  if (!noAuth) {
    //登录过期自动登录
    if (!store.state.app.token && !checkLogin()) {
      toLogin();
      return Promise.reject({
        msg: "未登录",
      });
    }
  }
  //normal Token
  if (
    store.state.app.token &&
    (url.split("/")[0] !== "employee" ||
      url === "employee/merchant/belong/List" ||
      url.includes("employee/merchant/active"))
  )
    if (str) {
      // delete header[TOKENNAME]
      header["Authorization"] = store.state.app.spareToken;
    } else {
      header[TOKENNAME] = store.state.app.token;
    }

  //manager Token
  if (
    store.state.app.managerToken &&
    url.split("/")[0] === "employee" &&
    url !== "employee/merchant/belong/List" &&
    !url.includes("employee/merchant/active")
  )
    if (str) {
      // delete header[TOKENNAME]
      header["Authorization"] = store.state.app.spareToken;
    } else {
      header[TOKENNAME] = store.state.app.token;
    }
  return new Promise((reslove, reject) => {
    // let urlApi = !str
    //   ? "https://admin.huikexin.fun/api/front/" + url
    //   : Url + "/" + url;
    let urlApi = "";
    if (str) {
      if (newOrder) {
        urlApi = "https://admin.huikexin.fun/front/" + url;
      } else {
        urlApi = Url + "/" + url;
      }
    } else {
      urlApi = "https://admin.huikexin.fun/api/front/" + url;
    }
    uni.request({
      url: urlApi,
      method: method || "GET",
      header: header,
      data: data || {},
      https: false, // app支持手机不校验Https
      success: (res) => {
        if (noVerify) reslove(res.data, res);
        else if (res.data.code == 200 || res.data.code == 1) {
          replaceHttpWithHttps(res.data);
          reslove(res.data, res);
        } else if (
          [410000, 410001, 410002, 401, 402].indexOf(res.data.code) !== -1
        ) {
          let routes = getCurrentPages();
          //获取当前页面路由
          let curRoute = routes[routes.length - 1].route;
          //工作台内页面跳转登录前，先跳转到个人中心，防止双token陷入登录循环
          if (curRoute.split("/")[1] === "admin") {
            uni.switchTab({
              url: "/pages/user/index",
            });
          }
          store.commit("LOGOUT");
          toLogin();
          reject(res.data);
        } else if (res.data.code == 500) {
          if (
            res.data.message &&
            res.data.message.indexOf("登录信息已过期") != -1
          ) {
            store.commit("LOGOUT");
          } else {
            uni.showToast({
              title: res.data.message || res.data.msg,
              icon: "none",
            });
          }
          reject(res.data.message || res.data.msg || "系统异常");
        } else if (res.data.code == 400) {
          reject(res.data.message || res.data.msg || "参数校验失败");
        } else if (res.data.code == 404) {
          reject(res.data.message || res.data.msg || "没有找到相关数据");
        } else if (res.data.code == 403) {
          reject(res.data.message || res.data.msg || "没有相关权限");
        } else reject(res.data.message || res.data.msg || "系统错误");
      },
      fail: (msg) => {
        reject("请求失败");
      },
    });
  });
}

const request = {};

["options", "get", "post", "put", "head", "delete", "trace", "connect"].forEach(
  (method) => {
    request[method] = (api, data, opt, params) =>
      baseRequest(
        api,
        method,
        data,
        opt || {},
        params,
        opt ? opt.newMark || false : false
      );
  }
);

export default request;
